﻿import pymysql  #导入 pymysql  
  
#打开数据库连接  
db= pymysql.connect(host="localhost",user="root",  
    password="root",db="news",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
#1.查询操作  
# 编写sql 查询语句  user 对应我的表名  
#insert into news(`title`,`source`,`time`) values(%s,%s,%s)" % (title,source,time)
sql_insert ="""insert into news(id,title,source,time) values(4,'liu','这个是中文','1')"""  
try:  
	print(sql_insert)
	cur.execute(sql_insert)    #执行sql语句  
	
	sql = "select * from news" 
	cur.execute(sql)
	results = cur.fetchall()    #获取查询的所有记录  
	print("id\ttitle\tsource\ttime")
	#遍历结果  
	for row in results :  
		id = row[0]  
		title = row[1]  
		source = row[2]  
		time = row[3]
		print(id,'\t',title,'\t',source,'\t',time)
except Exception as e:  
    raise e  
finally:  
    db.close()  #关闭连接  